import { server$ } from '@builder.io/qwik-city';
import { checkAuth } from '~/server/authn';
import { db } from '~/server/db';
import logger from '~/server/logger';
import { postTagService } from '~/server/service/user-tag-service';

export const searchTags = server$(async function (search: string) {
  const result = await checkAuth(this);
  if (!result.ok) {
    return [];
  }

  const tags = await postTagService.search(db, search, 10);
  logger.info('[searchTags]', { search, resultCount: tags.length });
  return tags;
});

export const createTag = server$(async function (name: string) {
  const result = await checkAuth(this);
  if (!result.ok) {
    throw new Error('未登录');
  }

  // TODO: 限流

  const tag = await postTagService.create(db, name);
  logger.info('[createTag]', { name, id: tag.id.toString() });
  return tag;
});
